/*
 * ESP32 传感器控制系统 - 传感器管理模块
 * 负责读取和管理传感器数据
 */

#include "sensor_manager.h"
#include "driver/adc.h"

// 全局变量
float temperature = 25.0;
float humidity = 60.0;
unsigned long last_sensor_read = 0;

void init_sensors() {
  // 初始化ADC
  adc1_config_width(ADC_WIDTH_BIT_12);
  adc1_config_channel_atten(TEMP_ADC_CHANNEL, ADC_ATTEN_DB_12);   // 温度传感器ADC通道
  adc1_config_channel_atten(HUMID_ADC_CHANNEL, ADC_ATTEN_DB_12);  // 湿度传感器ADC通道
}

void update_sensors() {
  unsigned long current_time = millis();
  if (current_time - last_sensor_read >= SENSOR_INTERVAL) {
    // 读取温度
    temperature = read_temperature();
    
    // 读取湿度
    humidity = read_humidity();
    
    last_sensor_read = current_time;
  }
}

float read_temperature() {
  // 模拟温度传感器读取 (基于ADC + 噪声)
  int temp_raw = adc1_get_raw(TEMP_ADC_CHANNEL);
  float temp_voltage = (temp_raw / 4095.0) * 3.3;
  float temp = 20.0 + (temp_voltage * 20.0) + random(-50, 50) / 100.0;
  
  // 限制范围
  return constrain(temp, -10.0, 50.0);
}

float read_humidity() {
  // 模拟湿度传感器读取
  int humid_raw = adc1_get_raw(HUMID_ADC_CHANNEL);
  float humid_voltage = (humid_raw / 4095.0) * 3.3;
  float humid = 40.0 + (humid_voltage * 30.0) + random(-100, 100) / 100.0;
  
  // 限制范围
  return constrain(humid, 0.0, 100.0);
}